package ATBMS.ucm;

import ATBMS.control.MainApp;
import ATBMS.control.RegisterUserControl;
import ATBMS.modles.DAO.DAOFactory;
import ATBMS.modles.DAO.UserDAO;
import ATBMS.modles.User;

/**
 * Register User Use Case Implement
 */
public class UCRegisterUser implements UCController {

    private RegisterUserControl ruc;

    public UCRegisterUser(RegisterUserControl ruc) {
        this.ruc = ruc;
    }

    public void run() {
        User newUser = ruc.getUserEditView().getInput();

        if (newUser != null) {
            String checkRet = checkUser(newUser);
            if (checkRet != null) {
                ruc.getUserEditView().alert(checkRet);
                return;
            }
            UserDAO userdao = DAOFactory.getUserDAO();
            if (userdao == null) {
                ruc.getUserEditView().alert("Can't Connect To DB!");
                return;
            }
            if (!userdao.insert(newUser)) {
                ruc.getUserEditView().alert(userdao.getErrorMessage());
            } else {
                ruc.getUserEditView().alert("  Congratulations " + newUser.getUname() + " !\r\n" +
                        "Register successed!Please login.");
            }
        } else {
            ruc.getUserEditView().alert("Internal Error");
            MainApp.getApplication().exit();
        }
    }

    static private String checkUser(User user) {

        if (user.getUname().length() == 0) {
            return ("User Name can't be null!");
        }
        if (user.getPassword().length() == 0 || user.getPassword2().length() == 0) {
            return ("Two password can't be null!");
        }
        if (user.getPassword().compareTo(user.getPassword2()) != 0) {
            return ("Two password is not same!");
        }
        if (user.getUaddr().length() == 0) {
            return ("Address can't be null!");
        }
        if (user.getUemail().length() == 0) {
            return ("E-Mail can't be null!");
        }
        if (user.getUtel().length() == 0) {
            return ("Telephone can't be null!");
        }
        return null;
    }
}
